<?php

namespace Api\Event;

/** 
 * 订阅接口
 * @author Legend. <xcx_legender@qq.com>
 function:

 * @param 
 * @return 
 */

class GameScribeEvent extends BaseEvent 
{


	/** 
	 * 获取我的订阅列表
	 * @author Legend. <xcx_legender@qq.com>
	 * @param int $uid; boolen $detail  是否只返回game_ids 数组
	 * @return 
	 */
	//modify for adding $p&$limit param at 2015/7/7 by susy.liang<liangling@ilongyuan.com.cn>
	public function mine($uid, $detail = false, $p=0, $limit=0)
	{
		$service = D('Common/GameScribe', 'Service');
		$map['uid'] = intval($uid);
		//$game_ids = $service->where($map)->getField('game_id', true);
		$res = $service->where($map);
		$p && $res = $res->page($p);
		$limit && $res = $res->limit($limit);
		$game_ids = $res->getField('game_id', true);
		if (!$detail)
		{
			return $game_ids;
		}
		else
		{
			$gEvent = A('Api/Game','Event');
			foreach ($game_ids as $game_id) {
				$game = $gEvent->info($game_id);
				if ($game)
				{
					$game['is_scribe'] = 1;
					$data[$game_id] = $game;
				}
			}
			return $data;
		}
	}


	/** 
	 * 获取用户订阅数
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	
	public function count_mine($uid)
	{
		$service = D('Common/GameScribe', 'Service');
		$map['uid'] = $uid;
		return $service->where($map)->count();
	}


	/** 
	 * 是否订阅
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	
	public function is_scribe($uid, $game_id)
	{
		if (!$uid || !$game_id)
		{
			return false;
		}
		$map['uid']     = intval($uid);
		$map['game_id'] = intval($game_id);
		$service = D('Common/GameScribe', 'Service');
		return $service->where($map)->count() > 0;
	}

	#ACTION

	/** 
	 * 添加订阅
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	
	public function scribe($uid, $game_id)
	{
		if (!$uid || !$game_id)
		{
			return;
		}
		$game = event('Game')->info(intval($game_id));
		if (!$game){
			return false;
		}
		$map['uid']     = intval($uid);
		$map['game_id'] = intval($game_id);
		$service = D('Common/GameScribe', 'Service');
		if (!$service->where($map)->find() )
		{
			$map['create_time'] = NOW_TIME;
			$res = $service->add($map);
			if ($res)
			{
				A('Api/Game', 'Event')->scribe($game_id);
			}	
			return ture;
		}
		return false;		
	}


	/** 
	 * 取消订阅
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	
	public function unscribe($uid, $game_id)
	{
		if (!$uid || !$game_id)
		{
			return;
		}
		$map['uid']     = intval($uid);
		$map['game_id'] = intval($game_id);
		$service = D('Common/GameScribe', 'Service');
		if ( $service->where($map)->find() )
		{
			$res = $service->where($map)->delete();	
			if ($res)
			{
				A('Api/Game', 'Event')->scribe($game_id, false);
			}
			return true;
		}
		return false;
	}

}